package com.hc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hc.util.IdWorker;
import com.hc.util.LoggerUtil;

@Controller
@RequestMapping(value = "File")
public class FileUtilsController extends BaseController {
	/**
	 * 
	 * @Description： 上传图片
	 * 
	 * @param files
	 * @param request
	 * @return
	 * @author:
	 * @since: 2017年5月19日 上午10:41:12
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public JSON threeFileUpload(@RequestParam("file") CommonsMultipartFile files[], HttpServletRequest req) {
		JSONArray keyArr = new JSONArray();
		FileOutputStream fos = null;
		InputStream in = null;
		File f = new File(FILE_PATH);
		if (!f.exists()) {
			f.mkdirs();
		}
		for (int i = 0; i < files.length; i++) {
			if (!files[i].isEmpty()) {
				String newFileName = IdWorker.createId();
				try {
					fos = new FileOutputStream(FILE_PATH + newFileName);
					in = files[i].getInputStream();
					int b = 0;
					while ((b = in.read()) != -1) {
						fos.write(b);
					}
				} catch (Exception e) {
					LoggerUtil.error(e);
				} finally {
					try {
						if (fos != null) {
							fos.close();
						}
						if (in != null) {
							in.close();
						}
					} catch (Exception e2) {
						LoggerUtil.error(e2);
					}
				}
				keyArr.add(newFileName);
			}
		}
		return Message(SUCCESS, "上传成功", keyArr);
	}

	/**
	 * 
	 * @Description： 获取图片文件
	 * 
	 * @param req
	 * @param resp
	 * @param key
	 * @author:
	 * @since: 2017年5月19日 上午10:40:45
	 */
	@RequestMapping("/getFile/{key}")
	public void getFile(HttpServletRequest req, HttpServletResponse resp, @PathVariable String key) {
		FileInputStream in = null;
		OutputStream out = null;
		try {
			File file = new File(FILE_PATH + key);
			if (!file.exists()) {
				return;
			}
			in = new FileInputStream(FILE_PATH + key);
			out = resp.getOutputStream();
			byte buffer[] = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			LoggerUtil.error(e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
	}
}
